﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Timers;
using System.Transactions;
using MINERP.BLL.Common;
using MINERP.COM;
using MINERP.DAL;
using MINERP.DAL.CommonDAL;

namespace MINERP.BLL.ProductConditionFile
{
    public class ProductConditionFileBLL
    {
        public ProductConditionFileBLL()
        {
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        }

        public delegate void ShowMessage(string str);//定义委托将处理信息传递到表示层
        public delegate void ShowProcess(int str);//定义委托将处理进度传递到表示层
        public delegate void ShowResult(OrderFileView orderFileView);//定义委托将处理结果传递到表示层

        private const string HEAD_OUTDEV = "[OutDevice]";
        private const string OUTDEV_DEVICENAME = "DeviceName=";
        private const string HEAD_INDEV = "[InDevice]";
        private const string INDEV_DEVICETYPE = "DeviceType=";
        private const string INDEV_DEVICENAEM = "DevieceName=";
        private const string HEAD_IMAGElIST = "[ImageList]";
        private const string IMG_IMAGECNT = "ImageCnt=";
        private const string IMG_FULLPATHNAME = "FullPathName=";
        private const string IMG_PRINTCNT = "PrintCnt=";
        private const string IMG_SIZENAME = "SizeName=";
        private const string IMG_BACKPRINT = "BackPrint=";
        private const string IMG_BACKPRINTLINE1 = "BackPrintLine1=";
        private const string IMG_BACKPRINTLINE2 = "BackPrintLine2=";
        private const string IMG_RESIZE = "Resize=";
        private const string IMG_DSC_CHK = "DSC_Chk=";
        private const string IMG_TRIMMING = "Trimming=";
        private const string IMG_DATATIMEPRINT = "DataTimePrint=";
        private const string IMG_DATATIME = "DataTime=";
        private const string IMG_ROTATION = "Rotation=";
        private const string IMG_ORIGINALFILENAME = "OriginalFileName=";
        private const string IMG_MULTILAYOUTID = "MultiLayoutId=";
        private const string HEAD_MULTILAYOUT = "[MultiLayout]";
        private const string MULTILAYOUT_LAYOUTFILENAME = "LayoutFileName=";
        private const string HEAD_ORDERINFONATION = "[OrderInfomation]";
        private const string ORDER_ORDERPATHNAME = "OrderPathName=";
        private const string ORDER_SERVERTYPE = "ServerType=";
        private const string ORDER_ORDERNUMBER = "OrderNumber=";
        private const string ORDER_SIZENAME = "SizeName=";
        private const string ORDER_PRINTCNT = "PrintCnt=";
        private const string ORDER_DECIDEORDERDATATIME = "DecideOrderDataTime=";
        private const string ORDER_TRANSFERORDERDATATIME = "TransfOrderDataTime=";
        private const string ORDER_TERMINALID = "TerminalId=";
        private const string ORDER_THUMBNAIL = "Thumbnail=";
        private const string ORDER_ORDER_STATUS = "Status=";
        private const string ORDER_ERRSTATUS = "ErrStatus=";
        private const string ORDER_BACKTETM = "BackTerm=";
        private const string ORDER_COMMENTCNT = "CommentCnt=";
        private const string HEAD_PLATFORM = "[Platform]";
        private const string PLATFORM_ID = "ID=";
        private const string PLATFORM_VERSION = "Version=";
        private const string STR_IPG = "IPG";
        private bool EnableProduct = false;
        Timer timer = new Timer();
        public int Techid { set; get; }
        public event ShowMessage ShowMsgHandle;
        public event ShowProcess ShowCurrPointHandle;
        public event ShowResult ShowLastResultHandle;

        /// <summary>
        /// 创建产品的Condition文件
        /// </summary>
        public int AutoPruductConditionFile()
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {

                int intDoingProduct = (int)OrderInfoStatus.Doing;
                int intProductConditionTech = (int)TechType.ProductCondition;
                int intDoingWorkFlow = (int)OrderFlowListStatus.Useable;
                orderInfo Order = null;
                int intCorrent = (int)OrderFileStatus.Corrented;
                OrderFile orderFile = db.OrderFile.FirstOrDefault(p => p.Status == intCorrent && p.orderInfo.status == 1);


                if (orderFile != null)
                {
                    orderFile.orderInfoReference.Load();
                    Order = orderFile.orderInfo;
                    if (Order == null)
                    {
                        Order =
                            db.orderInfo.Where(
                                p =>
                                p.status == intDoingProduct &&
                                p.WorkOrderFlowList.FirstOrDefault(
                                    pi =>
                                    pi.Status == intDoingWorkFlow && pi.tb_Tech.TechType == intProductConditionTech &&
                                    pi.Status == intDoingWorkFlow) != null).
                                OrderByDescending(pa => pa.Priority).FirstOrDefault();
                    }
                }
                else
                {
                    Order =
                           db.orderInfo.Where(
                               p =>
                               p.status == intDoingProduct &&
                               p.WorkOrderFlowList.FirstOrDefault(
                                   pi =>
                                   pi.Status == intDoingWorkFlow && pi.tb_Tech.TechType == intProductConditionTech &&
                                   pi.Status == intDoingWorkFlow) != null).
                               OrderByDescending(pa => pa.Priority).FirstOrDefault();
                }
                if (Order == null)
                {
                    //返回未找到,无要处理的产品
                    ShowCurrPointHandle(0);
                    ShowMsgHandle("当前没有要生成Condition的产品");
                    return 1;
                }
                List<orderInfo> listOrder = new List<orderInfo>();
                listOrder.Add(Order);

                string SaveFilePath = db.FileDirPath.FirstOrDefault(p => p.id == 3).FileDir; //文件存放位置
                foreach (orderInfo orderInfo in listOrder) //按照产品来分解Condition
                {
                    int initStatus = (int)OrderFileStatus.Created;//正常状态
                    string strErrRemark = "";
                    int currentProductNum = orderInfo.productNum;
                    orderInfo.Tb_ProductReference.Load();
                    orderInfo.Tb_Product.ProductPrintReference.Load();
                    ProductPrint pprint = orderInfo.Tb_Product.ProductPrint;
                    ShowCurrPointHandle(10);
                    if (pprint == null)
                    {
                        //触发错误 产品没有相应的打印名称                        
                        initStatus = (int)OrderFileStatus.CreateErr;
                        strErrRemark = "产品没有相应的打印名称";
                        //return 1;
                    }
                    orderInfo.photoInfo.Load();
                    Dictionary<string, int> dicPhoto = new Dictionary<string, int>();
                    //吧产品按照尺寸分好，一种尺寸产生一个condition文件
                    ShowMsgHandle("正在分解订单");
                    List<photoInfo> photoListOril = orderInfo.photoInfo.Where(p => p.status == (int)PhotoStatus.DistributedPrinter).ToList();//要生成的原照片列表
                    List<photoInfo> photoList = new List<photoInfo>();//要生成的实际照片列表

                    foreach (photoInfo list in photoListOril)
                    {
                        printer printer = db.printer.FirstOrDefault(p => p.PrinterID == list.printerId);
                        if (printer.PType == ((int)PrinterType.Enlarge).ToString())
                        {
                            photoList.Add(list);
                        }

                    }
                    //if (photoList)
                    foreach (photoInfo photo in photoList)
                    {
                        printer testPrinter = db.printer.FirstOrDefault(p => p.PrinterID == photo.printerId);
                        if (testPrinter == null)
                        {
                            ShowCurrPointHandle(0);
                            ShowMsgHandle("当前没有要生成Condition的产品");
                            //触发错误 照片未分配打印机将流程返回到分配打印机
                            if (!orderInfo.WorkOrderFlowList.IsLoaded)
                            {
                                orderInfo.WorkOrderFlowList.Load();
                            }
                            List<WorkOrderFlowList> listWof = orderInfo.WorkOrderFlowList.ToList();

                            foreach (WorkOrderFlowList wf in listWof)
                            {
                                if (!wf.tb_TechReference.IsLoaded)
                                {
                                    wf.tb_TechReference.Load();
                                }

                            }

                            WorkOrderFlowList disPhotoFlow = listWof.FirstOrDefault(p => p.tb_Tech.TechType == (int)TechType.DigitalOutput);
                            WorkOrderFlowList CurrFlow = listWof.FirstOrDefault(p => p.tb_Tech.TechId == Techid);
                            disPhotoFlow.Status = (int)OrderFlowListStatus.Useable;//流程改回到分配打印机
                            CurrFlow.Status = (int)OrderFlowListStatus.Wait;
                            db.SaveChanges();
                            return 0;

                        }
                        string photoSize = "";
                        if (photo.Height > photo.Width)
                        {
                            photoSize = photo.Height + "X" + photo.Width;

                        }
                        else
                        {
                            photoSize = photo.Width + "X" + photo.Height;
                        }
                        if (dicPhoto.ContainsKey(photoSize))
                        {
                            dicPhoto[photoSize]++;
                        }
                        else
                        {
                            dicPhoto.Add(photoSize, 1);
                        }
                    }

                    //string leftDota = "\""; //左引号
                    //string rightDota = "\""; //右引号
                    string leftDota = "";
                    string rightDota = "";
                    int orderInProduct = 0;
                    //ShowMsgHandle("正在生成condition文件");
                    ShowCurrPointHandle(30);
                    int conSplitNum;
                    if (dicPhoto.Count != 0)
                    {
                        conSplitNum = 60 / dicPhoto.Count;


                        int currPoint = 30;
                        ///生成condition
                        foreach (KeyValuePair<string, int> kvp in dicPhoto.OrderBy(p => p.Key))
                        {
                            try
                            {
                                StringBuilder strCondition = new StringBuilder();
                                OrderFile conditionFile = new OrderFile();
                                orderInProduct++;
                                ShowCurrPointHandle(currPoint += conSplitNum);
                                ShowMsgHandle("正在生成第" + orderInProduct + "个condition文件");
                                strCondition.AppendLine(HEAD_OUTDEV);
                                strCondition.AppendLine(OUTDEV_DEVICENAME + leftDota + "PICsRGB" + rightDota);
                                strCondition.AppendLine(HEAD_IMAGElIST);
                                //strCondition.AppendLine(IMG_IMAGECNT + leftDota + kvp.Value + rightDota);
                                List<photoInfo> CurrSizelist =
                                    photoList.Where(
                                        p =>
                                        (p.Width + "X" + p.Height) == kvp.Key || (p.Height + "X" + p.Width) == kvp.Key)
                                        .
                                        ToList();
                                int Num = 0;
                                CurrSizelist = CurrSizelist.OrderBy(s => s.photoName).ToList();
                                //CurrSizelist = CurrSizelist.OrderByDescending(s => s.photoName).ToList();
                                List<photoInfo> NumSizelist = CurrSizelist.Distinct(new PhotoComparer()).OrderBy(s => s.photoName).ToList();
                                strCondition.AppendLine(IMG_IMAGECNT + leftDota + NumSizelist.Count() + rightDota);
                                foreach (photoInfo photo in NumSizelist)
                                {
                                    Num++;
                                    strCondition.AppendLine(Num + "=" + leftDota + photo.photoName + rightDota);

                                }
                                int printTotal = 0; //照片总数
                                double totalHeigth = 0; //照片总长度
                                try
                                {
                                    CurrSizelist.FirstOrDefault().paperFaceReference.Load();
                                    CurrSizelist.FirstOrDefault().paperTypeReference.Load();
                                }
                                catch (Exception exx)
                                {
                                    //触发数据库错误
                                    WriteLogForCheck.WriteLogFile("初始照片时连接数据库未成功");
                                    return 0;

                                }

                                paperFace face = CurrSizelist.FirstOrDefault().paperFace;
                                paperType type = CurrSizelist.FirstOrDefault().paperType;
                                int printerid = Convert.ToInt32(CurrSizelist.FirstOrDefault().printerId);
                                #region //Old
                                //foreach (photoInfo photo in CurrSizelist)
                                //{
                                //    strCondition.AppendLine("[" + photo.photoName + "]"); //照片名称
                                //    strCondition.AppendLine(IMG_FULLPATHNAME + leftDota + photo.photoName + rightDota);
                                //    strCondition.AppendLine(IMG_PRINTCNT + leftDota + photo.TotalNum + rightDota);
                                //    //if (pprint == null)
                                //    //{
                                //    //    strCondition.AppendLine(IMG_SIZENAME + leftDota + "" + rightDota);
                                //    //}
                                //    //else
                                //    //{
                                //    //    strCondition.AppendLine(IMG_SIZENAME + leftDota +
                                //    //                            pprint.PrintSizeName + rightDota);
                                //    //}
                                //    if (photo.Width > photo.Height)
                                //    {
                                //        strCondition.AppendLine(IMG_SIZENAME + leftDota +
                                //                                photo.Height+"x"+photo.Width + rightDota);
                                //    }
                                //    else
                                //    {
                                //        strCondition.AppendLine(IMG_SIZENAME + leftDota +
                                //                                 photo.Width + "x" + photo.Height + rightDota);
                                //    }
                                //    strCondition.AppendLine(IMG_BACKPRINT + leftDota + "FREE" + rightDota);
                                //    string photoRemark = "";
                                //    if (photo.Remark.Length >= 40)
                                //    {
                                //        photoRemark = photo.Remark.Substring(0, 29);
                                //    }
                                //    else
                                //    {
                                //        photoRemark = photo.Remark;
                                //    }
                                //    strCondition.AppendLine(IMG_BACKPRINTLINE1 + leftDota + "*" + photo.photoId + "*" + orderInfo.OrderProductId +"*"+ photoRemark + rightDota);

                                //    strCondition.AppendLine(IMG_BACKPRINTLINE2 + leftDota + rightDota);
                                //    if (photo.Remark.IndexOf("cover", StringComparison.OrdinalIgnoreCase)>-1)//是cover
                                //    {
                                //        strCondition.AppendLine(IMG_RESIZE + leftDota + "FITIN" + rightDota);
                                //    }
                                //    else
                                //    {
                                //        strCondition.AppendLine(IMG_RESIZE + leftDota + "FILLIN" + rightDota);
                                //    }

                                //    if (photo.imageEnhancement != null)
                                //    {
                                //        strCondition.AppendLine(IMG_DSC_CHK + leftDota + ((bool)photo.imageEnhancement ? "TRUE" : "FALSE") + rightDota); //XML文件来
                                //    }
                                //    else
                                //    {
                                //        strCondition.AppendLine(IMG_DSC_CHK + leftDota + "FALSE" + rightDota); //XML文件来
                                //    }

                                //    strCondition.AppendLine(IMG_TRIMMING + leftDota + "0.0.0.0" + rightDota);
                                //    strCondition.AppendLine(IMG_ORIGINALFILENAME + leftDota + photo.photoName +
                                //                            rightDota);
                                //    printTotal += Convert.ToInt32(photo.TotalNum);
                                //    totalHeigth += photo.Height;
                                //    conditionFile.photoInfo.Add(photo);
                                //}
                                #endregion
                                //foreach (photoInfo photo in CurrSizelist)
                                foreach (var photoGroup in CurrSizelist.GroupBy(p => p.photoName))
                                {
                                    photoInfo photo = photoGroup.FirstOrDefault();
                                    strCondition.AppendLine("[" + photo.photoName + "]"); //照片名称
                                    strCondition.AppendLine(IMG_FULLPATHNAME + leftDota + photo.photoName + rightDota);
                                    int currPhotoPrintNum = currentProductNum*photoGroup.Count() * photo.TotalNum ?? 0;
                                    strCondition.AppendLine(IMG_PRINTCNT + leftDota + currPhotoPrintNum + rightDota);
                                    printTotal += currPhotoPrintNum;
                                    //if (pprint == null)
                                    //{
                                    //    strCondition.AppendLine(IMG_SIZENAME + leftDota + "" + rightDota);
                                    //}
                                    //else
                                    //{
                                    //    strCondition.AppendLine(IMG_SIZENAME + leftDota +
                                    //                            pprint.PrintSizeName + rightDota);
                                    //}
                                    if (photo.Width > photo.Height)
                                    {
                                        strCondition.AppendLine(IMG_SIZENAME + leftDota +
                                                                photo.Height + "x" + photo.Width + rightDota);
                                    }
                                    else
                                    {
                                        strCondition.AppendLine(IMG_SIZENAME + leftDota +
                                                                 photo.Width + "x" + photo.Height + rightDota);
                                    }
                                    strCondition.AppendLine(IMG_BACKPRINT + leftDota + "FREE" + rightDota);
                                    string photoRemark = "";
                                    if (photo.Remark.Length >= 40)
                                    {
                                        photoRemark = photo.Remark.Substring(0, 29);
                                    }
                                    else
                                    {
                                        photoRemark = photo.Remark;
                                    }
                                    strCondition.AppendLine(IMG_BACKPRINTLINE1 + leftDota + "*" + photo.photoId + "*" + orderInfo.OrderProductId + "*" + photoRemark + rightDota);

                                    strCondition.AppendLine(IMG_BACKPRINTLINE2 + leftDota + rightDota);
                                    if (photo.Remark.IndexOf("cover", StringComparison.OrdinalIgnoreCase) > -1)//是cover
                                    {
                                        strCondition.AppendLine(IMG_RESIZE + leftDota + "FITIN" + rightDota);
                                    }
                                    else
                                    {
                                        strCondition.AppendLine(IMG_RESIZE + leftDota + "FILLIN" + rightDota);
                                    }

                                    if (photo.imageEnhancement != null)
                                    {
                                        strCondition.AppendLine(IMG_DSC_CHK + leftDota + ((bool)photo.imageEnhancement ? "TRUE" : "FALSE") + rightDota); //XML文件来
                                    }
                                    else
                                    {
                                        strCondition.AppendLine(IMG_DSC_CHK + leftDota + "FALSE" + rightDota); //XML文件来
                                    }

                                    strCondition.AppendLine(IMG_TRIMMING + leftDota + "0.0.0.0" + rightDota);
                                    strCondition.AppendLine(IMG_ORIGINALFILENAME + leftDota + photo.photoName +
                                                            rightDota);
                                    //printTotal += Convert.ToInt32(photo.TotalNum);
                                    totalHeigth += photo.Height;
                                    List<photoInfo> photoIngroup = photoGroup.ToList();
                                    foreach (photoInfo p in photoIngroup)
                                    {
                                        conditionFile.photoInfo.Add(p);
                                    }

                                    //conditionFile.photoInfo.Add(photo);
                                }
                                strCondition.AppendLine(HEAD_ORDERINFONATION);
                                strCondition.AppendLine(ORDER_ORDERPATHNAME + leftDota + rightDota);
                                strCondition.AppendLine(ORDER_SERVERTYPE + leftDota + "2" + rightDota);

                                if (!orderInfo.Tb_OrderBagReference.IsLoaded)
                                {
                                    orderInfo.Tb_OrderBagReference.Load();
                                }
                                if (orderInfo.Tb_OrderBag.BagName.IndexOf('_') > 0)
                                {
                                    string strIPG = "";
                                    string strTemp = orderInfo.Tb_OrderBag.BagName.Split('_')[0];
                                    int currnetLength = strTemp.Length;
                                    int zroeLength = 7 - currnetLength;
                                    if (zroeLength > 0)
                                    {
                                        //  strIPG = STR_IPG + string.Format("{0:d" + zroeLength + "}", strTemp);
                                        string strZero = "";
                                        for (int i = 0; i < zroeLength; i++)
                                        {
                                            strZero += "0";
                                        }
                                        strIPG = STR_IPG + strZero + strTemp;
                                    }
                                    else if (zroeLength == 0)
                                    {
                                        strIPG = STR_IPG + strTemp;
                                    }
                                    else
                                    {
                                        strIPG = STR_IPG + strTemp.Substring(Math.Abs(zroeLength));
                                    }
                                    strCondition.AppendLine(ORDER_ORDERNUMBER + leftDota + strIPG + rightDota);
                                }
                                else
                                {
                                    strCondition.AppendLine(ORDER_ORDERNUMBER + leftDota + "0000000000" +
                                                            rightDota);
                                }
                                if (pprint == null)
                                {
                                    strCondition.AppendLine(ORDER_SIZENAME + leftDota + "" + rightDota);
                                }
                                else
                                {
                                    strCondition.AppendLine(ORDER_SIZENAME + leftDota + pprint.PrintSizeName + rightDota);

                                }
                                strCondition.AppendLine(ORDER_PRINTCNT + leftDota + printTotal + rightDota);
                                strCondition.AppendLine(ORDER_DECIDEORDERDATATIME + leftDota +
                                                        DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + rightDota);
                                string filePath = SaveFilePath + @"\" + orderInfo.OrderProductId + "_" + orderInProduct +
                                                  ".txt";
                                StreamWriter sw = null;
                                try
                                {
                                    ShowMsgHandle("正在保存第" + orderInProduct + "个condition文件");
                                    if (File.Exists(filePath))
                                    {
                                        File.Delete(filePath);
                                    }
                                    sw = File.CreateText(filePath);
                                    sw.Write(strCondition);
                                }

                                catch (Exception exx)
                                {
                                    //触发写文件错误
                                    ShowMsgHandle(orderInfo.OrderProductName + "写文件错误。请确认您有路径" + SaveFilePath + "的访问权限");
                                    strErrRemark += "写文件错误。请确认您有路径" + SaveFilePath + "的访问权限";
                                    initStatus = (int)OrderFileStatus.CreateErr;
                                }
                                finally
                                {
                                    sw.Close();
                                }
                                DateTime timeNow = CommonMethodDAL.GetServerTime();

                                conditionFile.ConditionFilePath = filePath;
                                conditionFile.createTime = timeNow;
                                conditionFile.FolderName = orderInfo.OrderProductId + "_" + orderInProduct;
                                conditionFile.lastPrintTime = timeNow;
                                conditionFile.Length = CurrSizelist.FirstOrDefault().Height;
                                //conditionFile.Width = orderInfo.Width;
                                conditionFile.Width = CurrSizelist.FirstOrDefault().Width;
                                //conditionFile.Width = orderInfo.Width;
                                conditionFile.orderInfo = orderInfo;
                                conditionFile.paperFace = face;
                                conditionFile.paperType = type;
                                conditionFile.printer = db.printer.FirstOrDefault(p => p.PrinterID == printerid);
                                conditionFile.Priority = Convert.ToInt32(orderInfo.Priority);
                                conditionFile.Remark = "";
                                conditionFile.Status = initStatus;
                                conditionFile.Remark = strErrRemark;
                                db.AddToOrderFile(conditionFile);
                                db.SaveChanges();
                                ShowLastResultHandle(new OrderFileView() { FolderName = conditionFile.FolderName, ConditionFilePath = filePath, CreateTime = timeNow, OrderFileID = conditionFile.OrderFileID, OrderProductid = orderInfo.OrderProductId, OrderProductName = orderInfo.OrderProductName, Remark = (string.IsNullOrEmpty(strErrRemark)) ? "OK" : strErrRemark, IsError = 0 });

                            }
                            catch (Exception)
                            {//触发数据库错误
                                WriteLogForCheck.WriteLogFile("数据保存时发生异常");
                                ShowMsgHandle("数据库连接失败请检查网络");
                                return 0;
                            }
                        } //同一产品内相同尺寸照片结束
                    }
                    else
                    {
                        OrderFile order = new OrderFile()
                                                      {
                                                          Status = (int)OrderFileStatus.CreateErr,
                                                          ConditionFilePath = "",
                                                          createTime = DateTime.Now,
                                                          FolderName = "",
                                                          lastPrintTime = DateTime.Now,
                                                          Length = 0,
                                                          paperFace = db.paperFace.FirstOrDefault(),
                                                          paperType = db.paperType.FirstOrDefault(),
                                                          printer = db.printer.FirstOrDefault(),
                                                          orderInfo = orderInfo,
                                                          Priority = 0,
                                                          Width = 0,
                                                          Remark = "产品无照片或者照片已经打印，不能生成Condition"
                                                      };
                        db.AddToOrderFile(order);
                        db.SaveChanges();
                        ShowLastResultHandle(new OrderFileView()
                                                 {
                                                     FolderName = "",
                                                     ConditionFilePath = "",
                                                     CreateTime = DateTime.Now,
                                                     OrderFileID = order.OrderFileID,
                                                     OrderProductid = orderInfo.OrderProductId,
                                                     OrderProductName = orderInfo.OrderProductName,
                                                     Remark = "产品无照片或者照片已经打印，不能生成Condition",
                                                     IsError = 1
                                                 });

                    }
                    if (!orderInfo.WorkOrderFlowList.IsLoaded)
                    {
                        orderInfo.WorkOrderFlowList.Load();
                    }

                    orderInfo.OrderFile.Load();
                    if ((orderInfo.OrderFile.Count == dicPhoto.Count) && photoList.Count > 0)//要正常结束的产品
                    {
                        WorkFlowListBLL workFlowListBll = new WorkFlowListBLL();
                        bool rtnBool = workFlowListBll.OverCurTech(Techid, db.users.FirstOrDefault().userID, orderInfo.OrderProductId);//修改产品的流程
                        if (!rtnBool)
                        {
                            //删除已经添加的信息
                            List<OrderFile> listOrderFile = orderInfo.OrderFile.ToList();
                            foreach (OrderFile of in listOrderFile)
                            {
                                db.DeleteObject(of);
                            }
                            ShowMsgHandle("产品" + orderInfo.OrderProductName + "未生成成功，正准备重新尝试");
                        }
                        else
                        {
                            ShowMsgHandle("产品" + orderInfo.OrderProductName + "生成成功");
                            ShowMsgHandle("当前没有要生成Condition的产品");
                        }

                    }
                    // else if ((orderInfo.OrderFile.Count != dicPhoto.Count) && orderInfo.photoInfo.Count > 0)
                    else if (orderInfo.OrderFile.Count != dicPhoto.Count)
                    {

                        ShowMsgHandle("正在修正出错产品");
                        //删除已经添加的信息
                        List<OrderFile> listOrderFile = orderInfo.OrderFile.ToList();
                        foreach (OrderFile of in listOrderFile)
                        {

                            ShowLastResultHandle(new OrderFileView() { FolderName = of.FolderName, ConditionFilePath = of.ConditionFilePath, CreateTime = of.createTime, OrderFileID = of.OrderFileID, OrderProductid = orderInfo.OrderProductId, OrderProductName = orderInfo.OrderProductName, Remark = (string.IsNullOrEmpty(strErrRemark)) ? "错误已修正。正在重新生成" : strErrRemark, IsError = 1 });
                            db.DeleteObject(of);
                        }
                        if (!orderInfo.WorkOrderFlowList.IsLoaded)
                        {
                            orderInfo.WorkOrderFlowList.Load();
                        }
                        foreach (WorkOrderFlowList wf in orderInfo.WorkOrderFlowList)
                        {
                            if (!wf.tb_TechReference.IsLoaded)
                            {
                                wf.tb_TechReference.Load();
                            }
                        }
                        WorkOrderFlowList CurrFlow = orderInfo.WorkOrderFlowList.FirstOrDefault(p => p.Status == (int)OrderFlowListStatus.Useable);
                        WorkOrderFlowList ProductFlow = orderInfo.WorkOrderFlowList.FirstOrDefault(p => p.tb_Tech.TechType == (int)TechType.ProductCondition);
                        if (CurrFlow != null && ProductFlow != null)
                        {
                            if (CurrFlow.WorkFlowListId == ProductFlow.WorkFlowListId)
                            {
                                ProductFlow.Status = CurrFlow.Status = (int)OrderFlowListStatus.Useable;
                            }
                            else
                            {
                                ProductFlow.Status = (int)OrderFlowListStatus.Useable; //流程改回到生产condition
                                CurrFlow.Status = (int)OrderFlowListStatus.Wait;
                            }
                        }
                        else
                        {

                        }
                        ShowMsgHandle("当前没有要生成Condition的产品");

                    }
                    else
                    {

                    }
                    db.SaveChanges();
                    ShowCurrPointHandle(0);

                } //产品结束
            }
            return 0;

        }
        public void StartProduct()
        {
            AutoPruductConditionFile();
            timer.Interval = 30000;//30秒
        }
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {

            try
            {
                timer.Enabled = false;
                AutoPruductConditionFile();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (EnableProduct)
                {
                    timer.Enabled = true;
                }
                else
                {
                    timer.Enabled = false;
                }
            }

        }
        public void EndProduct()
        {
            EnableProduct = false;
        }
    }
    public class OrderFileView
    {
        public int OrderFileID { get; set; }
        public int OrderProductid { get; set; }
        public string OrderProductName { get; set; }
        public string FolderName { get; set; }
        public string ConditionFilePath { get; set; }
        public DateTime CreateTime { get; set; }
        public string Remark { get; set; }
        public int IsError { get; set; }//1 正常0错误
    }
    public class PhotoComparer : IEqualityComparer<photoInfo>
    {
        public bool Equals(photoInfo x, photoInfo y)
        { return x.photoName.Equals(y.photoName); }
        public int GetHashCode(photoInfo obj) { return 0; }
    }
}
